extends TimeLord

var _i = 0
var _j = 0
var wave_offset = 0
var moving_offset = 0
var color = Color8(0,0,0,255)
var shader = load('res://shaders/block_shader.shader')
var margin = 0.07
var Mat

var RISE_TIME = 0.2
var OVERALL_TIME = 0.5
var FALL_TIME = OVERALL_TIME - RISE_TIME

var EXPANDED_MARGIN = 0.3
var HIGHLIGHTED_COLOR = Color8(255,0,255,255)


const BLOCK_MOVE_ANITIME = 0.3 #this is to be referenced even if MOVE_ANITIME is overriden

var MOVE_ANITIME = BLOCK_MOVE_ANITIME

class_name Block

export var inert = true

onready var Grid = find_parent("GRID")

func _ready():
	Mat=ShaderMaterial.new()
	Mat.shader=shader
	Mat.set_shader_param("color",color)
	Mat.set_shader_param("margin",margin)
	$TextureRect.material = Mat

func _process(delta):
	if inert:
		var residual = _i - floor(_i)
		if (residual != 0):
			var dy = Grid.displacement[ceil(_i)] - Grid.displacement[floor(_i)]
			wave_offset = Grid.displacement[floor(_i)] + residual*dy
		else:
			if _i in range(len(Grid.displacement)):
				wave_offset = Grid.displacement[_i]
			else:
				wave_offset = Grid.displacement[0]
		position = Vector2(0, wave_offset) + Vector2(_i,-_j)*Grid.BLOCKSIZE

func move_to(i,j, delay=0, time=MOVE_ANITIME, easing = Tween.EASE_OUT):
	_prepare_action()
	var tw1 = SDTween.new()
	tw1.interpolate_property(self,"_i",_i,i,time,Tween.TRANS_CUBIC,easing,delay)
	add_child(tw1)
	tw1.start()

	var tw2 = SDTween.new(self,"_prepare_action")
	tw2.interpolate_property(self,"_j",_j,j,time,Tween.TRANS_CUBIC,easing,delay)
	add_child(tw2)
	tw2.start()

func destructing_sound():
	var p = SDRandPitch2D.new("res://sounds/erasure.ogg")
	p.position = position
	get_parent().add_child(p)
	p.play()

func erase(with_sound = false):
	if with_sound:
		destructing_sound()
	Grid.Blocks.erase(self)
	queue_free()

func _prepare_action():
	_i = round(_i)
	_j = round(_j)
	rotation = 0

func block_pulsate():
	var ani_progress = 0

	var colortw1 = SDTween.new()
	colortw1.interpolate_property($TextureRect,"material:shader_param/color",$TextureRect.material.get_shader_param("color"),HIGHLIGHTED_COLOR,RISE_TIME,Tween.TRANS_CUBIC,Tween.EASE_OUT)
	add_child(colortw1)
	colortw1.start()

	var margintw1 = SDTween.new()
	margintw1.interpolate_property($TextureRect,"material:shader_param/margin",$TextureRect.material.get_shader_param("margin"),EXPANDED_MARGIN,RISE_TIME,Tween.TRANS_CUBIC,Tween.EASE_OUT)
	add_child(margintw1)
	margintw1.start()

	ani_progress+=RISE_TIME

	var colortw2 = SDTween.new()
	colortw2.interpolate_property($TextureRect,"material:shader_param/color",HIGHLIGHTED_COLOR,color,FALL_TIME,Tween.TRANS_CUBIC,Tween.EASE_OUT,ani_progress)
	add_child(colortw2)
	colortw2.start()

	var margintw2 = SDTween.new()
	margintw2.interpolate_property($TextureRect,"material:shader_param/margin",EXPANDED_MARGIN,margin,FALL_TIME,Tween.TRANS_CUBIC,Tween.EASE_OUT,ani_progress)
	add_child(margintw2)
	margintw2.start()
